<?php

namespace app\admin\controller\auth;

use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\Session;

/**
 * 管理员充值记录管理
 *
 * @icon fa fa-circle-o
 */
class Adminrecharge extends Backend
{
    
    /**
     * AdminRechargeLog模型对象
     * @var \app\admin\model\AdminRechargeLog
     */
    protected $model = null;
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('AdminRechargeLog');
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','admin_id','admin_name','title','type','value','user_id','user_name','ip','createtime']);
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 用户充值
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if($params['value'] <=0)
                {
                    $this->error('充值金额有误');
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    //  根据手机号或者id判断用户是否存在
                    $user = new User();
                    $recharge_user = $user->whereOr(['id' => $params['user_id'], 'mobile' => $params['user_id']])->find();

                    if (!$recharge_user)
                    {
                        $this->error('充值用户不存在');
                    }

                    //  充值类型
                    $value = $params['value'];$type =$params['type'];
                    if ($type == 1)
                        $recharge_user_update = ['cny' => $recharge_user->cny + $value];
                    else if ($type == 2)
                        $recharge_user_update = ['sac' => $recharge_user->sac + $value];
                    else
                        $this->error('充值类型有误');

                    $params['user_name'] = $recharge_user->nickname;
                    $params = array_merge($params,$this->default_add_data());   //  添加默认操作数据

                    //  开启事务
                    Db::startTrans();
                    $recharge_user->save($recharge_user_update);    //  用户充值
                    if ($this->auth->show != 0)
                    {
                        //  如果不是0，都判断为小后台账号，添加记录
                        $this->model->allowField(true)->save($params);    //  添加充值记录
                        if ($type == 1)
                            account_log($recharge_user->id,$value,$recharge_user->cny+$recharge_user->freeze_cny,0,$recharge_user->sac,'平台管理员充值');
                        else
                            account_log($recharge_user->id,0,$recharge_user->cny+$recharge_user->freeze_cny,$value,$recharge_user->sac,'平台管理员充值');
                    }else{
                        //  如果是小后台账号，记录到back表
                        Db::name('admin_recharge_log_back')->insert($params);
                        if ($type == 1)
                            $this->account_log($recharge_user->id,$value,$recharge_user->cny+$recharge_user->freeze_cny,0,$recharge_user->sac,'平台管理员充值');
                        else
                            $this->account_log($recharge_user->id,0,$recharge_user->cny+$recharge_user->freeze_cny,$value,$recharge_user->sac,'平台管理员充值');
                    }
                    Db::commit();
                } catch (DbException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('充值成功');
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }

        //  默认展示视图
        return $this->view->fetch();
    }

    /**
     * 插入操作默认数据
     * @return array
     */
    private function default_add_data()
    {
        return [
            'admin_id'      =>  $this->auth->id,
            'admin_name'    =>  $this->auth->username,
            'title'         =>  '平台充值',
            'ip'            =>  request()->ip(),
            'createtime'    =>  time(),
        ];
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $this->error('删除功能下线');
    }

    private function account_log($user_id, $cny, $cny_balance, $sac, $sac_balance, $desc,$cny_freeze = '', $deal_sn = '', $order_sn = '',$type='1')
    {
        $data = [
            'user_id' => $user_id,
            'cny' => $cny,
            'cny_balance' => $cny_balance,
            'sac' => $sac,
            'sac_balance' => $sac_balance,
            'desc' => $desc,
            'cny_freeze' => $cny_freeze,
            'deal_sn' => $deal_sn,
            'order_sn' => $order_sn,
            'type' => $type,
            'change_time' => time(),
        ];
        Db::name('user_account_log_back')->insert($data);
    }
}
